<template>
  <page-meta :page-style="'overflow:'+(show?'hidden':'visible')">
    <view class="container">
      <view>
        <view class="bg-linear-gradient-pink-bottom" style="height: 25vh;">
          <image style="height: 20vh;margin-top: 4vh;" src="@/static/legion/bg-title.png" mode="aspectFit" />
        </view>

        <view>
          <view class="view-card-box bg-linear-gradient-pink-right" @tap="goPage(pages[0])">
            <uni-grid :column="2" :showBorder="false" :square="false" :highlight="false">
              <uni-grid-item>
                <view class="view-block-center">
                  <image class="item-img" src="@/static/legion/register.png" mode="aspectFit" />
                </view>
              </uni-grid-item>
              <uni-grid-item>
                <view class="text-left" style="line-height: 60px;">
                  <text class="text-white text-xxl">信息填报</text>
                </view>
              </uni-grid-item>
            </uni-grid>
          </view>

          <view class="view-card-box bg-linear-gradient-pink-right" style="height: 60px;" @tap="goPage('/')">
            <uni-grid :column="2" :showBorder="false" :square="false" :highlight="false">
              <uni-grid-item>
                <view class="view-block-center">
                  <image class="item-img" src="@/static/legion/reservation.png" mode="aspectFit" />
                </view>
              </uni-grid-item>
              <uni-grid-item>
                <view class="text-left" style="line-height: 60px;">
                  <text class="text-white text-xxl">预约筛查</text>
                </view>
              </uni-grid-item>
            </uni-grid>
          </view>

          <view class="view-card-box bg-linear-gradient-pink-right" style="height: 60px;" @tap="goPage('/')">
            <uni-grid :column="2" :showBorder="false" :square="false" :highlight="false">
              <uni-grid-item>
                <view class="view-block-center">
                  <image class="item-img" src="@/static/legion/register.png" mode="aspectFit" />
                </view>
              </uni-grid-item>
              <uni-grid-item>
                <view class="text-left" style="line-height: 60px;">
                  <text class="text-white text-xxl">报告查询</text>
                </view>
              </uni-grid-item>
            </uni-grid>
          </view>

          <view class="view-card-box bg-linear-gradient-pink-right" style="height: 60px;" @tap="goPage('/')">
            <uni-grid :column="2" :showBorder="false" :square="false" :highlight="false">
              <uni-grid-item>
                <view class="view-block-center">
                  <image class="item-img" src="@/static/legion/register.png" mode="aspectFit" />
                </view>
              </uni-grid-item>
              <uni-grid-item>
                <view class="text-left" style="line-height: 60px;">
                  <text class="text-white text-xxl">个人信息</text>
                </view>
              </uni-grid-item>
            </uni-grid>
          </view>
        </view>
      </view>

      <view>
        <uni-popup ref="popup" type="top" :mask-click="false">
          <view class="service-box bg-white text-content-xl">
            <view class="text-center">
              <text class="text-black text-xxl text-bold">用户服务协议与隐私政策</text>
            </view>
            <view class="text-xl text-black">
              <text>欢迎使用两癌筛查服务助手小程序，在您使用小程序服务前，请认真阅读</text>
              <text class="text-blue" @tap="viewUserServiceAgreement">《用户服务协议》</text>
              <text>和</text>
              <text class="text-blue" @tap="viewPrivacyPolicy">《隐私政策》</text>
              <text>全部条款。我们非常重视您的用户权益与个人信息的保护，我们将通过上述协议向您说明我们如何为您提供服务并保障您的用户权益，如您同意，请点击“同意”接受我们的服务。</text>
            </view>
            <view class="text-center margin-top-xl">
              <button size="mini" class="btn-df text-white" @tap="toAgree">同意</button>
            </view>
          </view>
          <uni-popup ref="extraPopup">
            <view class="service-box-inner-one bg-white text-content-xl">
              <view class="right-top-close" @tap="viewClose">
                <uni-icons type="closeempty" size="25" color="#000000"></uni-icons>
              </view>
              <view v-if="userServiceAgreement">
                <view class="text-center">
                  <text class="text-black text-xxl text-bold">用户服务协议</text>
                </view>
                <scroll-view style="height: 60vh;" :scroll-y="true">
                  <view class="text-xl text-black">
                    <text>用户服务协议</text>
                  </view>
                </scroll-view>
              </view>
              <view v-if="privacyPolicyBool">
                <view class="text-center">
                  <text class="text-black text-xxl text-bold">隐私政策</text>
                </view>
                <scroll-view style="height: 60vh;" :scroll-y="true">
                  <view class="text-xl text-black">
                    <text>隐私政策</text>
                  </view>
                </scroll-view>
              </view>
              <view class="text-center">
                <button class="btn-df text-white" @tap="viewClose">确定</button>
              </view>
            </view>
          </uni-popup>
        </uni-popup>
      </view>
    </view>
  </page-meta>
</template>

<script setup>
  import NP from 'number-precision'

  const hospitalUrl = ref('/interface/getHospital')
  const dictDataUrl = ref('/interface/getDictByType')
  const addressUrl = ref('/interface/getAddress')
  const checkAreaUrl = ref('/interface/getCheckArea')

  const show = ref(false)
  const popup = ref()
  const extraPopup = ref()
  // 用户服务协议
  const userServiceAgreement = ref(false)
  // 隐私政策
  const privacyPolicyBool = ref(false)

  const pages = ref([
    '/pages/patientArchive/patientArchive',
  ])

  onLoad((options) => {
    console.log('1');
    // #ifdef MP-WEIXIN
    console.log('参数', options);
    if (!util.judgeNull(options) && Object.keys(options).length > 0) {
      util.sharedParameterAnalysis(options);
    }
    // #endif
  })
  onShow(() => {
    console.log('2');
    if (util.judgeNull(uni.getStorageSync('Token'))) {
      // #ifdef MP-WEIXIN
      http.noTokenShowModal('请先登录', 'pages/index/index');
      // #endif
      return
    }
    getAllData()
  })
  onMounted(async () => {
    console.log('3');
    if (!util.judgeNull(uni.getStorageSync('Token'))) {
      let userInfo = uni.getStorageSync('loginUserInfo') || {};
      if ((util.judgeNull(userInfo.agreeAgreementPolicy) || userInfo.agreeAgreementPolicy == '0') &&
        popup.value) {
        popup.value.open();
        return;
      }
    }
  })
  onPullDownRefresh(() => {
    // 模拟加载
    setTimeout(() => {
      getAllData()
      uni.stopPullDownRefresh(); // 停止下拉刷新
    }, 100)
  })

  async function getAllData() {
    console.log('查询数据');
    // getIndexImgs()
    // getNoticeList()
    // 医院
    let hospitalList = uni.getStorageSync('hospitalRange');
    if (util.judgeNull(hospitalList)) {
      hospitalList = await getHospital();
      uni.setStorageSync('hospitalRange', hospitalList);
    }
    // 民族
    let nationList = uni.getStorageSync('nationRange');
    if (util.judgeNull(nationList)) {
      nationList = await loadDictData('nation');
      uni.setStorageSync('nationRange', nationList);
    }
    // 学历
    let educationList = uni.getStorageSync('educationRange');
    if (util.judgeNull(educationList)) {
      educationList = await loadDictData('education');
      uni.setStorageSync('educationRange', educationList);
    }
    // 户籍类型
    let censusList = uni.getStorageSync('censusRange');
    if (util.judgeNull(censusList)) {
      censusList = await loadDictData('census');
      uni.setStorageSync('censusRange', censusList);
    }
    // 婚姻状况
    let marriageList = uni.getStorageSync('marriageRange');
    if (util.judgeNull(marriageList)) {
      marriageList = await loadDictData('marriage');
      uni.setStorageSync('marriageRange', marriageList);
    }
    // 地址
    let provinceList = uni.getStorageSync('provinceRange');
    if (util.judgeNull(provinceList)) {
      provinceList = await loadAddressData('0');
      uni.setStorageSync('provinceRange', provinceList);
    }
    // 筛查对象来源
    let sourceList = uni.getStorageSync('sourceRange');
    if (util.judgeNull(sourceList)) {
      sourceList = await loadDictData('source');
      uni.setStorageSync('sourceRange', sourceList);
    }
    // 检查地
    let checkAreaList = uni.getStorageSync('checkAreaRange');
    if (util.judgeNull(checkAreaList)) {
      checkAreaList = await getCheckArea('0');
      uni.setStorageSync('checkAreaRange', checkAreaList);
    }
  }

  /**
   * 加载轮播图
   */
  const getIndexImgs = () => {
    http.get('/indexImgs').then(({
      data
    }) => {
      indexImgs.value = data;
      seq.value = data;
    })
  }

  const getNoticeList = () => {
    // 加载公告
    http.get('/shop/notice/topNoticeList').then(({
      data
    }) => {
      news.value = data;
    })
  }

  /**
   * 跳转公告列表页面
   */
  const onNewsPage = () => {
    uni.navigateTo({
      url: '/pages/recent-news/recent-news'
    })
  }

  async function getHospital() {
    return new Promise((resolve, reject) => {
      http.post(hospitalUrl.value, {
        parentId: null
      }).then((res) => {
        let result = res.result || [];
        let hospitalList = [];
        result.forEach(item => {
          hospitalList.push({
            value: item.value,
            text: item.title,
          });
        })
        resolve(hospitalList);
      })
    })
  }

  async function loadDictData(type) {
    return new Promise((resolve, reject) => {
      http.post(dictDataUrl.value, {
        type: type
      }).then((res) => {
        let result = res.result || [];
        let dictDataList = [];
        result.forEach(item => {
          dictDataList.push({
            value: item.value,
            text: item.title,
          });
        })
        resolve(dictDataList);
      })
    })
  }

  async function loadAddressData(parentId) {
    return new Promise((resolve, reject) => {
      http.post(addressUrl.value, {
        parentId: parentId
      }).then((res) => {
        let result = res.result || [];
        resolve(result);
      })
    })
  }

  async function getCheckArea(id) {
    return new Promise((resolve, reject) => {
      http.post(checkAreaUrl.value, {
        parentId: id
      }).then((res) => {
        let result = res.result || [];
        let checkAreaList = [];
        result.forEach(item => {
          checkAreaList.push({
            value: item.value,
            text: item.title,
          });
        })
        resolve(checkAreaList);
      })
    })
  }

  const goPage = (page) => {
    // #ifdef MP-WEIXIN
    if (util.judgeNull(uni.getStorageSync('Token'))) {
      http.noTokenShowModal('请先登录', 'pages/index/index');
      return;
    }
    // #endif
    let userInfo = uni.getStorageSync('loginUserInfo') || {}
    if ((util.judgeNull(userInfo.agreeAgreementPolicy) || userInfo.agreeAgreementPolicy == '0') && popup.value) {
      popup.value.open();
      return;
    }
    uni.navigateTo({
      url: page
    })
  }

  const viewUserServiceAgreement = () => {
    console.log("用户服务协议");
    userServiceAgreement.value = true;
    privacyPolicyBool.value = false;
    extraPopup.value.open('top');
  }
  const viewPrivacyPolicy = () => {
    console.log("隐私政策");
    userServiceAgreement.value = false;
    privacyPolicyBool.value = true;
    extraPopup.value.open('top');
  }
  const viewClose = () => {
    extraPopup.value.close();
  }
  const toAgree = () => {
    uni.showLoading({
      title: '加载中'
    });
    http.post('/sys/agreeAgreementPolicy').then((res) => {
      let result = res.result || {}
      wx.setStorageSync('loginUserInfo', result.userInfo || {});
      popup.value.close();
    }).finally(() => {
      uni.hideLoading();
    })
  }
</script>

<style scoped lang="scss">
  @use './index.scss';
</style>
